package phonebook;

import com.andro.chansung.R;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

public class PhoneListAdapter extends BaseAdapter {
	private Phone phone;
	private LayoutInflater inflater;
	private Activity activity;
	private ViewHolder viewHolder;
	
	public PhoneListAdapter(Activity activity, Phone phone) {
		this.phone = phone;
		this.activity = activity;
		this.inflater = LayoutInflater.from(activity);
	}
	
	private class ViewHolder {
		public TextView titleTv;
		public Button   callBtn;
	}
	
	public int getCount() {
		return phone.getPhoneNumbers().keySet().toArray().length;
	}

	public String getItem(int position) {
		return (String)phone.getPhoneNumbers().keySet().toArray()[position];
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View view = convertView;
		
		if( view == null ) {
			viewHolder = new ViewHolder();
			view = inflater.inflate(R.layout.phone_book_list_view_cell_layout, null);
			viewHolder.titleTv = (TextView)view.findViewById(R.id.phone_book_list_view_cell_title_tv);
			viewHolder.callBtn = (Button)view.findViewById(R.id.phone_book_list_view_cell_call_btn);
			view.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder)view.getTag();
		}
		
		String innerParty = getItem(position);
		viewHolder.titleTv.setText(innerParty);
		viewHolder.callBtn.setText(phone.getPhoneNumbers().get(innerParty));
		viewHolder.callBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Uri number = Uri.parse("tel:" + ((Button)v).getText());
				Intent dial = new Intent(Intent.ACTION_DIAL, number);
				activity.startActivity(dial);
			}
		});
		
		return view;
	}
}
